// const baseUrl = "http://2qjb53.natappfree.cc";
const baseUrl = "https://ericlliao.mynatapp.cc";

const QQMAPKEY = "LYXBZ-MCOLQ-ZL55D-G4ZIH-ZWIJK-IHBH4";

const Api = {
	getWxUserInfoByCode: '/wxMini/getWxUserInfoByCode',
	updateToken: '/wxMini/updateToken',
	getSessionByCode: '/wechat/getSessionByCode',
	getMenulist: '/mpMenu/list',
	sendPlace: '/svcPosition/add',
	sendUserCode: '/wxMini/getWxUserInfoByCode',
	getLoginStatus: '/wxMini/getLoginStatus',
	getPositionStatus: '/svcPosition/positionStatus',
	detail: '/svcRecord/detail',
	delete: '/svcPosition/delete',
	finishServe: '/svcRecord/finishServe',
	listByUser: '/svcRecord/listByUser',
	addCard: '/svcWarrantyCard/add',
	deletesvcRecord: '/svcRecord/delete',
	listCountOnMini: '/svcWarrantyCard/listCountOnMini',
	logout: '/wxMini/logout',
	sys_login: '/wxMini/login',
	s_listCount: '/svcRecord/listCount',
	s_detail: '/svcWarrantyCard/detail',
	s_edit: '/svcWarrantyCard/edit',
	s_getDoorType: '/svcDict/getDoorType',
	s_getLockType: '/svcDict/getLockType',
	s_list: '/svcWarrantyCard/listOnMini',
	s_detailOnMini: '/svcWarrantyCard/detailOnMini'

}
const contentType = {
	form: "application/x-www-form-urlencoded",
	json: "application/json"
}
const getApi = (keyName) => {
	return Api[keyName]
}

const setUserInfo = (userinfo) => {
	uni.setStorage({
		key: 'User_info',
		data: userinfo,
		success: function() {
			console.log('success save userinfo');
		}
	});
}
let failRes = {};
let failNum = 0;
const getUserInfo = () => {
	return new Promise((resolve, reject) => {
		try {
			uni.getStorage({
				key: 'User_info',
				success: (res) => {
					console.log('get userinfo', res.data);
					resolve(res)
				},
				fail: (err) => {
					console.log('get userinfo fail', err);
					reject(err)
				}
			});
		} catch (e) {
			console.log('get userinfo fail', e);
		}

	})
}
const postApi = (url, method, options) => {
	return new Promise((resolve, reject) => {
		if (options.loading) {
			uni.showLoading({
				title: '加载中...'
			})
		}
		const token = uni.getStorageSync('User_token');
		uni.request({
			url: baseUrl + getApi(url),
			method: method || 'POST',
			data: options.dataType === 'json' ? JSON.stringify(options.data) : options.data,
			dataType: options.dataType,
			header: {
				Authorization: options.useToken === false ? '' : token,
				"Content-Type": options.contentType ? contentType[options.contentType] : contentType.json //区分请求头 默认为：application/json
			},
			success: function(res) {
				console.log('请求成功请求返回数据：', res)
				if (res.data.code === 200 && res.statusCode === 200) {
					resolve(res.data)
				} else if (res.data.code === 1011008) { //token过期
					uni.showToast({
						title: "登录信息失效，重新登录",
						icon: "none",
						duration: 2000,
						position: 'bottom',
						success() {
							upToken().then(() => {
								if (url !== "sys_login") {
									postApi(url, method, options)
								}
							})
						}
					});
				} else if (res.data.code === 42001) {
					console.log('出现了')
					failNum = failNum + 1;
					if (failNum >= 2) {
						uni.showToast({
							title: "网络繁忙，请退出重试",
							icon: "none"
						});
						reject("网络繁忙，请退出重试")
						return
					}
					wx.login({
						success: (ress) => {
							let {
								encryptedData,
								iv,
								signature,
								rawData
							} = failRes;
							let {
								nickName,
								gender,
								language = "",
								city = "",
								province = "",
								country,
								avatarUrl
							} = JSON.parse(rawData)
							console.log('ress', ress)
							postApi('sys_login', 'POST', {
								data: {
									code: ress.code,
									nickName,
									gender,
									language,
									city,
									province,
									country,
									avatarUrl
								},
								loading: true
							}).then(info => {
								console.log('获取token', info)
								uni.setStorageSync('User_token', info.data
									.token);
								uni.setStorageSync('User_tokenTime', info
									.data.expireTime);

								res.userInfo.id = info.data.wxUserId;
								res.userInfo.wxUserLevel = info.data
									.wxUserLevel;
								res.userInfo.wxUserNo = info.data.wxUserNo;

								uni.setStorageSync('User_info', res
									.userInfo);
								if (isuptoken) {
									upToken()
								} else if (cb) {
									cb(res.userInfo)
									return;
								} else {
									return res.userInfo;
								}
								uni.hideLoading()
							}).catch(err => {
								console.log('err', err)
							})
						}
					})
				} else if (res.data.success == false) {
					uni.showToast({
						title: res.data.message,
						icon: "none"
					});
					reject(res.data.message)
				}
			},
			fail: function(err) {
				uni.showToast({
					title: "服务器错误，请稍后重试",
					icon: "none"
				});
				reject(err)
			},
			complete: function(end) {
				uni.hideLoading()
			}
		})
	})
}
const upToken = () => {
	return new Promise((resovle, reject) => {
		let token = uni.getStorageSync('User_token');
		uni.request({
			url: baseUrl + getApi('updateToken'),
			method: 'GET',
			header: {
				Authorization: token,
				"Content-Type": contentType.json
			},
			success: info => {
				console.log('更新token', info)
				if (info.data && info.data.code == 10002) { //获取授权失败
					getUserProfile(true)
					return
				} else if (info.data.code == 1011008) {
					getUserProfile(true)
					return
				}
				let data = info.data.data;
				let userinfo = {
					avatarUrl: data.avatarUrl,
					nickName: data.nickName,
					userId: data.userId,
					version: data.version,
					wxUserId: data.wxUserId,
					wxUserLevel: data.wxUserLevel,
					wxUserNo: data.wxUserNo
				}
				uni.setStorageSync('User_token', data.token);
				uni.setStorageSync('User_tokenTime', data.expireTime);
				uni.setStorageSync('User_info', userinfo);
				const pages = getCurrentPages();
				const perpage = pages[pages.length - 1];
				perpage.onLoad()
				resovle(info)

			},
			fail: function(err) {
				uni.showToast({
					title: "服务器错误，请稍后重试",
					icon: "none"
				});
				reject(err)
			},
		})
	})
}
const getUserProfile = (isuptoken, cb, text) => {
	wx.showModal({
		title: '提示',
		content: text || '正在请求您的个人信息！',
		success(res) {
			if (res.confirm) {
				wx.getUserProfile({
					desc: "用于完善会员资料",
					success: (res) => {
						wx.login({
							success: (ress) => {
								let {
									encryptedData,
									iv,
									signature,
									rawData
								} = res;
								let {
									nickName,
									gender,
									language = "",
									city = "",
									province = "",
									country,
									avatarUrl
								} = JSON.parse(rawData)
								failRes = JSON.parse(JSON.stringify(res))
								postApi('sys_login', 'POST', {
									data: {
										code: ress.code,
										nickName,
										gender,
										language,
										city,
										province,
										country,
										avatarUrl
									},
									loading: true
								}).then(info => {
									console.log('获取token', info)
									console.log('typeof isuptoken', typeof isuptoken)
									uni.setStorageSync('User_token', info
										.data.token);
									uni.setStorageSync('User_tokenTime',
										info.data.expireTime);

									res.userInfo.id = info.data.wxUserId;
									res.userInfo.wxUserLevel = info.data
										.wxUserLevel;
									res.userInfo.wxUserNo = info.data
										.wxUserNo;

									uni.setStorageSync('User_info', res
										.userInfo);
									if (isuptoken && (typeof isuptoken =='boolean')) {
										upToken();
									} else if (cb) {
										cb(res.userInfo)
										return;
									} else {
										const pages = getCurrentPages();
										const perpage = pages[pages.length - 1];
										perpage.onLoad()
										//return res.userInfo;
									}
									uni.hideLoading()
								}).catch(err => {
									console.log('err', err)
								})
							}
						})
						console.log('授权的res', res)
					},
					fail: res => {
						//拒绝授权
						wx.showErrorModal('您拒绝了请求');
						return;
					}
				})
			} else if (res.cancel) {
				//拒绝授权 showErrorModal是自定义的提示
				//that.showErrorModal('您拒绝了请求');
				return;
			}
		}
	})

}
const com = {
	postApi,
	getApi,
	QQMAPKEY,
	setUserInfo,
	getUserInfo,
	upToken,
	getUserProfile
}

export {
	com
}
